package com.example.teacherservice.controller;

import com.example.teacherservice.dto.ClassDetailDTO;
import com.example.teacherservice.dto.StudentProgressDTO;
import com.example.teacherservice.repository.TeacherClassDetailRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/spoc/teacher-class-detail")
public class TeacherClassDetailController {

    private final TeacherClassDetailRepository teacherClassDetailRepository;

    public TeacherClassDetailController(TeacherClassDetailRepository teacherClassDetailRepository) {
        this.teacherClassDetailRepository = teacherClassDetailRepository;
    }

    @GetMapping("/{teacherId}/{classId}")
    public ResponseEntity<ClassDetailDTO> getClassDetail(
            @PathVariable Long teacherId,
            @PathVariable Long classId) {

        // 验证教师是否教授该班级
        boolean isTeaching = teacherClassDetailRepository.existsByTeaIdAndClassId(teacherId, classId);
        if (!isTeaching) {
            throw new IllegalArgumentException("教师未教授该班级");
        }

        // 获取班级详情
        ClassDetailDTO detail = new ClassDetailDTO();
        detail.setClassInfo(teacherClassDetailRepository.findClassById(classId));
        detail.setStudents(teacherClassDetailRepository.findStudentsByClassId(classId));
        detail.setCourses(teacherClassDetailRepository.findCoursesByClassId(classId));

        return ResponseEntity.ok(detail);
    }

    @GetMapping("/check-teaching-permission")
    public ResponseEntity<Boolean> checkTeachingPermission(
            @RequestParam Long teacherId,
            @RequestParam Long courseId) {
        boolean hasPermission = teacherClassDetailRepository.existsByTeaIdAndCourseId(teacherId, courseId);
        return ResponseEntity.ok(hasPermission);
    }

    @GetMapping("/student-progress/{teacherId}/{classId}/{studentId}")
    public ResponseEntity<List<StudentProgressDTO>> getStudentProgress(
            @PathVariable Long teacherId,
            @PathVariable Long classId,
            @PathVariable Long studentId) {

        // 1. 验证教师是否教授该班级
        if (!teacherClassDetailRepository.existsByTeaIdAndClassId(teacherId, classId)) {
            throw new IllegalArgumentException("教师未教授该班级");
        }

        // 2. 直接查询教师在该班级教授的课程ID（优化后的方法）
        List<Long> courseIds = teacherClassDetailRepository.findTeachingCourseIds(teacherId, classId);

        if (courseIds.isEmpty()) {
            return ResponseEntity.ok(Collections.emptyList());
        }

        // 3. 查询进度
        List<StudentProgressDTO> progressList = teacherClassDetailRepository
                .findStudentProgress(studentId, courseIds);

        return ResponseEntity.ok(progressList);
    }
}